package com.carey.myblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carey.myblog.pojo.Comment;
import com.carey.myblog.service.CommentService;
import com.carey.myblog.mapper.CommentMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* @author carey-
* @description 针对表【t_comment】的数据库操作Service实现
* @createDate 2022-05-28 13:44:05
*/
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
    implements CommentService{

    @Override
    public List<Comment> listCommentByBlogId(Long blogId) {
        List<Comment> comments = baseMapper.selectAllByBlogId(blogId,0L);
        //将1级评论（各自的子类，都归类2级评论）
        for (Comment sonComment: comments){
            List<Comment> twoComm = new ArrayList<>(); //用于存放：各个2级评论的（2级评论，包含所有子代）
            this.recursion(twoComm, sonComment);            //递归：查询当前sonComment子代，全放入2级评论
            sonComment.setReplyComments(twoComm);      //将2级评论：设置为1级评论的子代
        }
        return comments;          //返回评论
    }

    @Override
    public void saveComment(Comment comment) {
        Long parentCommentId = comment.getParentComment().getId();
        if (parentCommentId != -1){
            comment.setParentCommentId(parentCommentId);
            comment.setParentComment(baseMapper.selectById(parentCommentId));

        }else {
            comment.setParentComment(null);
        }
        baseMapper.insert(comment);
    }

    @Override
    public void deleteByBlogId(Long blogid) {
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("blog_id",blogid);
        baseMapper.delete(wrapper);
    }

    //递归：查询当前sonComment子代，全放入2级评论
    private void recursion(List<Comment> twoComm, Comment sonComment){
        if(sonComment != null){     //首先判断：子代是否为null
            //不为null则：查询到它的下一代
            List<Comment> comments = baseMapper.selectAllByParentCommentId(sonComment.getId());
            //判断该节点是否有回复
            if (comments.size()>0){
                for(Comment comment:comments){
                    //需要重新设置ParentComment
                    comment.setParentComment(baseMapper.selectById(comment.getParentCommentId()));
                    //将当前：子节点，放入2级评论
                    twoComm.add(comment);
                    //对该子节点：进一步递归判断
                    recursion(twoComm, comment);
                }
            }

        }
    }
}




